// packages/group/pages/manage-target-open/index.js
const app = getApp();
import { ManageTargetInfoUpdateMixins } from '../../../behaviors/page';
import { TARGET_TYPE } from '../../../constants/common';
import { PACKAGE_STAR_PAGE, PACKAGE_STORE_PAGE } from '../../../constants/route';
import { navTo, navToAction, redirectTo, showLoading, hideLoading } from '../../../common/env';
import { getPreBrandList } from '../../../api/brd';
import { getPreStoreList } from '../../../api/sto';
let loaded = false;

Page({
    mixins: [ManageTargetInfoUpdateMixins],
    data: {
        TARGET_TYPE,
        tab: TARGET_TYPE.brand,
        tabs: [
            { value: TARGET_TYPE.brand, name: '品牌主页' },
            { value: TARGET_TYPE.store, name: '店铺主页' },
        ],
        openList: [],
    },
    onLoad(options) {
        const { tab } = options;
        this.setData({ tab }, async () => {
            await this._handleGetList();
        });
    },
    async _handleGetList() {
        !loaded && showLoading('加载中...');
        const { tab = TARGET_TYPE.brand } = this.data;
        let openList = [];
        if (tab === TARGET_TYPE.brand) {
            openList = await getPreBrandList();
            if (!loaded && (!openList || !openList.length)) {
                redirectTo(PACKAGE_STAR_PAGE['brandOpen']);
            }
        } else if (tab === TARGET_TYPE.store) {
            openList = await getPreStoreList();
        }
        this.setData({
            openList,
        });
        if (!loaded) hideLoading(); loaded = true;
    },
    handleTabChange(e) {
        const { name } = e.detail;
        this.setData({ tab: name }, () => {
            this._handleGetList();
        });
    },
    handleNavToEditBrand(e) {
        const { remotePkOfBrand } = e.detail;
        if (remotePkOfBrand) {
            const preBrandInfo = this.data.openList.find(i => i.remotePkOfBrand === remotePkOfBrand);
            navToAction(PACKAGE_STAR_PAGE['brandOpen'], {
                remotePkOfBrand,
            }, {
                success(res) {
                    setTimeout(() => {
                        app.event.trigger('sendPreBrandInfo', preBrandInfo);
                    }, 800);
                },
            });
        } else {
            navTo(PACKAGE_STAR_PAGE['brandOpen']);
        }
    },
    handleNavToEditBrandExt() {
        navTo(PACKAGE_STAR_PAGE['brandOpen']);
    },
    handleNavToEditStore(e) {
        const { brandId, brandDistributorId } = e.detail;
        navTo(PACKAGE_STORE_PAGE['storeOpen'], {
            brandId,
            distributorId: brandDistributorId
        });  
    },
})
